<template>
  <div class="login_container">
    <div class="contain">
      <div class="avatar">
        <img src="../assets/logo.png" />
      </div>
      <el-form :model="loginForm" :rules="loginrules" ref="loginFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input prefix-icon="iconfont icon-3702mima" type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456',
      },
      loginrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度至少在6个字符', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    async login() {
      console.log(11)
      this.$refs.loginFormRef.validate(async (valid) => {
        //如果验证失败
        if (!valid) return

        //验证成功
        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error('登陆失败')
        this.$message.success('登录成功')
        console.log(res);

        //把从服务器返回的用户token值保存到sessionstorage中
        window.sessionStorage.setItem('token', res.data.token)
        //通过编程式导航跳转到 home 页面
        this.$router.push('/home')
      })
    },
    reset() {
      this.$refs.loginFormRef.resetFields()
    },
  },
}
</script>

<style lang="less" scoped>
.login_container {
  height: 100%;
  background-color: #2b4b6b;
}
.contain {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 450px;
  height: 300px;
  border-radius: 3px;
  background-color: #fff;
  .el-input {
    width: 300px;
  }
  .el-form {
    position: absolute;
    bottom: 0;
  }
  .avatar {
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 130px;
    height: 130px;
    background-color: #fff;
    border-radius: 50%;
    border: 1px solid #efefef;
    padding: 10px;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }
  .btns {
    display: flex;
    justify-content: flex-end;
  }
}
</style>

